﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IdentityModel.Tokens;
using System.Threading;
using System.Runtime.InteropServices;
using PSE.Framework.Caching;

namespace PSE.Framework.Common.Security.Services.Authentication.ClientCredentials
{
    [Serializable]
    public class IssuedTokenCache
    {
        private static Mutex _mtx = new Mutex();
        private static readonly string AppDomainName = "IssuedTokenCache Singleton AppDomain";
        private static IssuedTokenCache _instance;
        private Dictionary<KeyValuePair<string, string>, GenericXmlSecurityToken> _internalCache;
        private object locker;
        private string CacheEntryName = "IssuedTokenCache";
        private TimeSpan CacheTimeOut = new TimeSpan(0, 30, 0);
        
        public IssuedTokenCache()
        {
            locker = new object();
        }

        public void AddToken(GenericXmlSecurityToken token, string tokenId, string host)
        {
            if (String.IsNullOrEmpty(tokenId))
                throw new ArgumentNullException("tokenId");

            if (String.IsNullOrEmpty(tokenId))
                throw new ArgumentNullException("host");

            _mtx.WaitOne();
            {
                GetInternalCache();
                _internalCache.Add(new KeyValuePair<string, string>(tokenId, host), token);
            }
            _mtx.ReleaseMutex();
        }

        public bool TryGetToken(string tokenId, string host, out GenericXmlSecurityToken cachedToken)
        {
            if (String.IsNullOrEmpty(tokenId))
                throw new ArgumentNullException("tokenId");

            if (String.IsNullOrEmpty(host))
                throw new ArgumentNullException("host");

            _mtx.WaitOne();
            {
                GetInternalCache();

                cachedToken = null;

                GenericXmlSecurityToken tmp;

                KeyValuePair<string, string> key = new KeyValuePair<string, string>(tokenId, host);

                if (_internalCache.TryGetValue(key, out tmp))
                {
                    if (tmp.ValidTo < DateTime.UtcNow + TimeSpan.FromMinutes(1))
                        this._internalCache.Remove(key);
                    else
                        cachedToken = tmp;
                }
            }
            _mtx.ReleaseMutex();

            return (cachedToken != null);
        }

        private void GetInternalCache()
        {
            if (!Cache.Contains(CacheEntryName) || Cache.GetData(CacheEntryName) == null)
            {
                _internalCache = new Dictionary<KeyValuePair<string, string>, GenericXmlSecurityToken>();
                Cache.Add(CacheEntryName, _internalCache, CacheTimeOut);
            }
            else
            {
                _internalCache = Cache.GetData(CacheEntryName) as Dictionary<KeyValuePair<string, string>, GenericXmlSecurityToken>;
            }
        }

        private static AppDomain GetAppDomain(string friendlyName)
        {
            IntPtr enumHandle = IntPtr.Zero;
            Interop.mscoree.CorRuntimeHostClass host = new Interop.mscoree.CorRuntimeHostClass();
            try
            {
                host.EnumDomains(out enumHandle);

                object domain = null;
                while (true)
                {
                    host.NextDomain(enumHandle, out domain);
                    if (domain == null)
                    {
                        break;
                    }
                    AppDomain appDomain = (AppDomain)domain;
                    if (appDomain.FriendlyName.Equals(friendlyName))
                    {
                        return appDomain;
                    }
                }
            }
            finally
            {
                host.CloseEnum(enumHandle);
                Marshal.ReleaseComObject(host);
                host = null;
            }
            return null;
        }

        public static IssuedTokenCache GetInstance()
        {
            try
            {
                _mtx.WaitOne();

                if (_instance == null)
                {
                    AppDomain appDomain = GetAppDomain(AppDomainName);

                    if (appDomain == null)
                    {
                        appDomain = AppDomain.CreateDomain(AppDomainName);
                    }

                    Type type = typeof(IssuedTokenCache);
                    IssuedTokenCache instance = (IssuedTokenCache)appDomain.GetData(type.FullName);

                    if (instance == null)
                    {
                        instance = (IssuedTokenCache)appDomain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);

                        appDomain.SetData(type.FullName, instance);
                    }

                    _instance = instance;
                }
            }
            finally
            {
                _mtx.ReleaseMutex();
            }

            return _instance;
        }
    }
}